import React, {Component, Fragment} from 'react';
import {Button, Form, message, Icon, Tooltip} from 'antd';
import reportFormApi from "@/services/reportForm";
import ReportTableConfigModal from './ReportTableConfigModal'

@Form.create()
export default class HkReportTable extends Component {
  state = {
    visible: false,
    allReportData: [],
    conditionCache: [],
    currentCondition: null,
    currentConditionIndex: 0
  };

  componentDidMount() {
    // this.fetchData();
  }
  
  componentWillReceiveProps(nextProps) {
    if (nextProps.isLock !== this.props.isLock) {
      this.setState({
        allReportData: [],
        conditionCache: [],
      });
    }
  }

  fetchData = payload => {
    const s = {
      begin: '2020-08-01 00:00:00',
      end: '2020-12-01 00:00:00', // 时间区间-结束时间
      action: '1', // 营销场景-action
      position: '2', // 营销场景-position
      channel: '21', // 营销场景-channelId
      productId: '',
      shopName: '',
    };
    return reportFormApi.queryReportForm(payload).then(res => {
      if (res) {
        const { currentConditionIndex } = this.state
        const allReportDataCopy = [...this.state.allReportData]
        const conditionCacheCopy = [...this.state.conditionCache]
        if (this.state.currentCondition) {
          conditionCacheCopy[currentConditionIndex] = payload
          allReportDataCopy[currentConditionIndex] = res
        } else {
          conditionCacheCopy.push(payload)
          allReportDataCopy.push(res)
        }
        this.setState({
          conditionCache: conditionCacheCopy,
          allReportData: allReportDataCopy,
          currentConditionIndex: 0,
          currentCondition: null
        });
      }
    })
  }
  
  edit = (index) => {
    this.setState({
      visible: true,
      currentCondition: this.state.conditionCache[index],
      currentConditionIndex: index
    });
  };

  handleShowAdd = () => {
    if (!this.props.isLock) {
      message.warning('请先锁定查询条件');
    } else {
      this.setState({
        visible: true,
        currentCondition: null
      });
    }
  };

  onCancel = () => {
    this.setState({
      visible: false,
    });
  };

  renderChannelContent = channels => {
    if (Array.isArray(channels) && channels.length) {
      const keys = Object.keys(channels[0])
      const hasCheckChannel = this.props.checkedCondition.includes('渠道来源')
      if (!hasCheckChannel) {
        keys.shift()
      }
      
      return (
        <Fragment>
          {keys.map(key => {
            return (
              <tr key={key}>
                {channels.map(value => {
                  return <td key={value.channelName} className={key === 'channelName'?'condition': ''}>{value[key]}</td>;
                })}
              </tr>
            );
          })}
        </Fragment>
      );
    }
    return null
  }
  
  renderTableHeaderField = (field) => {
    if (this.props.checkedCondition.includes(field)) {
      return (
        <tr><td className="condition">{field}</td></tr>
      )
    }
    return null
  }
  
  renderChannelHeader = ()=> {
    if (!this.state.allReportData.length) {
      return null;
    }
    const hasCheckChannel = this.props.checkedCondition.includes('渠道来源')
    const hasCheckProductId = this.props.checkedCondition.includes('商品名称')
    return (
      <div className="chart-table first">
        <table className="header-table">
          <tbody>
          <tr><td className="condition">时间区间</td></tr>
          {this.renderTableHeaderField('营销场景')}
          {this.renderTableHeaderField('商户名称')}
          {
            hasCheckProductId ? (
              <tr><td className="condition">商品名称</td></tr>
            ): null
          }
          {
            hasCheckChannel? (
              <tr><td className="channel ">渠道来源</td></tr>
            ) : null
          }
          <tr><td>下单总量</td></tr>
          <tr><td>未支付主动取消</td></tr>
          <tr><td>
            未支付主动取消率
            <Tooltip title="未支付主动取消/下单总量">
              <Icon type="question-circle" />
            </Tooltip>
          </td></tr>
          <tr><td>支付失败</td></tr>
          <tr><td>支付失败率
            <Tooltip title="支付失败/（下单总量-未支付主动取消）">
              <Icon type="question-circle" />
            </Tooltip>
          </td></tr>
          <tr><td>支付超时</td></tr>
          <tr><td>支付超时率
            <Tooltip title="支付超时/（下单总量-未支付主动取消-支付失败）">
              <Icon type="question-circle" />
            </Tooltip>
          </td></tr>
          <tr><td>支付总数
            <Tooltip title="下单总量-未支付主动取消-支付失败-支付超时">
              <Icon type="question-circle" />
            </Tooltip>
          </td></tr>
          <tr><td>支付转化率
            <Tooltip title="支付总数/下单总量">
              <Icon type="question-circle" />
            </Tooltip>
          </td></tr>
          <tr><td>系统风控拒绝</td></tr>
          <tr><td>系统风控拒绝率
            <Tooltip title="系统风控拒绝/支付总数">
              <Icon type="question-circle" />
            </Tooltip></td></tr>
          <tr><td>商家审批订单数</td></tr>
          <tr><td>商家拒绝</td></tr>
          <tr><td>商家拒绝率
            <Tooltip title="商家拒绝/商家审批订单数">
              <Icon type="question-circle" />
            </Tooltip>
            </td></tr>
          <tr><td>平台审批订单数</td></tr>
          <tr><td>平台拒绝</td></tr>
          <tr><td>平台拒绝率
            <Tooltip title="平台拒绝/平台审批订单数">
              <Icon type="question-circle" />
            </Tooltip></td></tr>
          <tr><td>风控+人工审批拒绝率
            <Tooltip title="（平台拒绝+商家拒绝+系统风控拒绝）/支付总数">
              <Icon type="question-circle" />
            </Tooltip></td></tr>
          <tr><td>已支付主动取消</td></tr>
          <tr><td>已支付主动取消率
            <Tooltip title="已支付主动取消/（支付总数-平台拒绝-商家拒绝-系统风控拒绝）">
              <Icon type="question-circle" />
            </Tooltip></td></tr>
          <tr><td>待审批</td></tr>
          <tr><td>待发货</td></tr>
          <tr><td>成交订单</td></tr>
          <tr><td>成交/支付
            <Tooltip title="成交订单/支付总数">
              <Icon type="question-circle" />
            </Tooltip></td></tr>
          <tr><td>成交/下单
            <Tooltip title="成交订单/下单总量">
              <Icon type="question-circle" />
            </Tooltip></td></tr>
          </tbody>
        </table>
      </div>
    );
  };

  renderEmpty = () => {
    const len = this.state.allReportData.length
    if ( len === 12) {
      return null
    }
    const classNames = `chart-table empty ${len ? '' : 'no-data'}`
    return (
      <div className={classNames}>
        <div className="table-chart-empty" onClick={this.handleShowAdd}>
          +
        </div>
      </div>
    );
  };

  renderContent = (reportData, index) => {
    const { checkedCondition, } = this.props
    const { orderReportFormChannel: channels = [], begin, end, action, channel, position, shopName, productName  } = reportData;
    const channelLen = channels.length
    const beginNoSec = begin && begin.substr(0, 16) || ''
    const endNoSec = end && end.substr(0, 16) || ''
  
    return (
      <div key={reportData.begin} className="report-table-item">
        <div className="hk-chart-content-action">
          <Button type="primary" size={'small'} onClick={()=>this.edit(index)}>修改</Button>
        </div>
        <div className="chart-table">
          <div className="df">
            <table>
              <tbody>
              <tr>
                <td className="condition" colSpan={channelLen}>({beginNoSec}，{endNoSec}]</td>
              </tr>
              
                {
                  checkedCondition.includes('营销场景') ? (
                      <tr>
                        <td className="condition" colSpan={channelLen}>{action}-{position}-{channel}</td>
                      </tr>
                  ) : null
                }
                {
                  checkedCondition.includes('商户名称') ? (
                      <tr>
                        <td className="condition" colSpan={channelLen}>{shopName}</td>
                      </tr>
                  ) : null
                }
              {
                checkedCondition.includes('商品名称') ? (
                  <tr>
                    <td className="condition product-name" colSpan={channelLen}>
                      <Tooltip title={productName}>{productName}</Tooltip>
                    </td>
                  </tr>
                ) : null
              }
              { this.renderChannelContent(channels) }
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );
  };

  render() {
    const { checkedCondition, isLock } = this.props;
    const { visible, allReportData, currentCondition } = this.state;
    return (
      <div className="report-table-container">
        {this.renderChannelHeader()}
        {allReportData.map((reportData, index) => {
          return this.renderContent(reportData, index);
        })}
        {this.renderEmpty()}
        <ReportTableConfigModal
          isLock={isLock}
          visible={visible}
          onCancel={this.onCancel}
          checkedCondition={checkedCondition}
          fetchData={this.fetchData}
          currentCondition={currentCondition}
        />
      </div>
    );
  }
}
